package com.proj.hot.activity;

import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.SurfaceHolder;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.proj.hot.GlobalParams;
import com.proj.hot.R;
import com.proj.hot.utils.TimeUtil;

import org.json.JSONObject;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.IOException;
import java.util.ArrayList;

/**
 * 播放器播放页
 *
 */
public class VODBuyPlayActivity extends BaseActivity implements MediaPlayer.OnPreparedListener, MediaPlayer.OnBufferingUpdateListener, MediaPlayer.OnCompletionListener,
        MediaPlayer.OnErrorListener, MediaPlayer.OnInfoListener {

    private final String TAG = getClass().getSimpleName();


    String mVideoUrl="123";


    MediaPlayer mPlayer;
    VodVideoView mVideoView;
    SurfaceHolder mSurfaceHolder;
    int mLastPosition = -1;


    //播放控制相关
    RelativeLayout mVideoViewParentLayout;
    RelativeLayout mBufferingPage;
    TextView mBufferingHint;
//    private ViewGroup mVgInfo;
    private ViewGroup mVgControlPanel;
    private SeekBar mSeekBar;
    private TextView mTvCurrentPosition;
    private TextView mTvDuration;
    private ImageView playbtn;


    //延迟自动隐藏
    private Handler mPanelDelayHideHandler;
    private Runnable mPanelDelayHideRunnable;
    private ArrayList<View> mNeedDelayHideViews;


    private String contentid;
//    private String goodsORtrave;//goods商品  trave旅游

//    TextView priceTV,phoneTV;

    boolean isback=false;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            switch (msg.what) {
                case 0:

                    try {

                        mPlayer.stop();
                        mPlayer.reset();
                        mLastPosition = 0;
                        startupPlay();

                    } catch (Exception e) {

                    }


                    break;

                case 1:

                    startupPlay();


                    break;


            }
        }
    };





    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_vodbuy_player);


        contentid=getIntent().getStringExtra("contentid");
//        goodsORtrave=getIntent().getStringExtra("goodsORtrave");

        mVideoUrl="http://115.29.35.134:443/file/videoviewdemo.mp4";
        mVideoUrl="http://v3.365yg.com/a0c00bf9b285c689e0c36b3e76cd2d2d/5986f1b2/video/m/2206da2c405dcf84615b897fc916ab1afdb11470c900002688f8c97bc0/";

        mBufferingPage = (RelativeLayout) findViewById(R.id.vod_buffering_hint_page);
        mBufferingHint = (TextView) findViewById(R.id.tv_buffering_progress);

        mVideoViewParentLayout = (RelativeLayout) findViewById(R.id.vod_player_view_parent);
        RelativeLayout.LayoutParams videoViewParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
        videoViewParams.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);
        mVideoView = new VodVideoView(this);
        mVideoView.setLayoutParams(videoViewParams);
        mVideoViewParentLayout.addView(mVideoView, 0);

        mSurfaceHolder = mVideoView.getHolder();
        mSurfaceHolder.addCallback(new SurfaceHolder.Callback() {
            @Override
            public void surfaceCreated(SurfaceHolder holder) {
                if (mPlayer == null) {

                    try{

                        AssetFileDescriptor afd = getApplicationContext().getResources().openRawResourceFd(R.raw.videoviewdemo);//获取raw下的视频文件  ;

                        mPlayer = new MediaPlayer();
                        mPlayer.setScreenOnWhilePlaying(true);
                        mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                        mPlayer.setLooping(true);
                        mPlayer.setOnPreparedListener(VODBuyPlayActivity.this);
                        mPlayer.setOnBufferingUpdateListener(VODBuyPlayActivity.this);
                        mPlayer.setOnCompletionListener(VODBuyPlayActivity.this);
                        mPlayer.setOnErrorListener(VODBuyPlayActivity.this);
                        mPlayer.setOnInfoListener(VODBuyPlayActivity.this);


                        mPlayer.setDataSource(/*"/sdcard/ceshi.mp4"*/afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());


                    }catch (Exception e){

                    }

                }
            }

            @Override
            public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
                if (mPlayer != null) {
                    mPlayer.setDisplay(holder);
                    if (!mPlayer.isPlaying()) {
                        startupPlay();
                    }
                }
            }

            @Override
            public void surfaceDestroyed(SurfaceHolder holder) {
            }
        });


        //播放控制相关
//        mVgInfo = (ViewGroup) findViewById(R.id.view_vod_info_hint);
        mVgControlPanel = (ViewGroup) findViewById(R.id.view_vod_control_panel);
        mSeekBar = (SeekBar) findViewById(R.id.sk_vod_seek_bar);
        playbtn=(ImageView) findViewById(R.id.playbtn);
        mTvCurrentPosition = (TextView) findViewById(R.id.tv_vod_current_positon);
        mTvDuration = (TextView) findViewById(R.id.tv_vod_duration);


        //延迟隐藏
        mPanelDelayHideHandler = new Handler();
        mNeedDelayHideViews = new ArrayList<>();



//        priceTV=(TextView) findViewById(R.id.price);
//        phoneTV=(TextView) findViewById(R.id.phone);

//        getPlayUrl();
//        getContent();


        mHandler.sendEmptyMessage(1);

    }



//    private void gotoBuy(){
//
//        Intent intent;
//        if (goodsORtrave.equals("goods")){
//            intent = new Intent(this, GoodsDetailActivity.class);
//        }else{
//            intent = new Intent(this, TraveDetailActivity.class);
//        }
//
//        intent.putExtra("contentid",contentid);
//        startActivity(intent);
//        this.finish();
//
//    }



    private void startupPlay() {
        if(mPlayer!=null) {//10月25日添加 防止空指针
            if (mVideoUrl == null || mPlayer.isPlaying())
                return;

            mBufferingPage.setVisibility(View.GONE);
            try {
//                mPlayer.setDataSource(mVideoUrl);


//                AssetFileDescriptor afd = this.getResources().openRawResourceFd(R.raw.videoviewdemo);//获取raw下的视频文件  ;
//
//                mPlayer.setDataSource(/*"/sdcard/ceshi.mp4"*/afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());


                mPlayer.prepareAsync();

                mHandler.sendEmptyMessageDelayed(1, 1000);


            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (SecurityException e) {
                e.printStackTrace();
            } catch (IllegalStateException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }



    private void updatePanelInfo() {
        if (mPlayer != null && mPlayer.isPlaying()) {
            int duration = mPlayer.getDuration();
            int current = mPlayer.getCurrentPosition();

            mTvDuration.setText(TimeUtil.secToTime(duration / 1000));
            mTvCurrentPosition.setText(TimeUtil.secToTime(current / 1000));
            mSeekBar.setProgress(current * mSeekBar.getMax() / duration);
            mSeekBar.postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (mVgControlPanel.getVisibility() == View.VISIBLE) {
                        updatePanelInfo();
                    }
                }
            }, 1000);
        }

    }



    private void showControlPane() {
        if (!mVgControlPanel.isShown()) {
            mVgControlPanel.startAnimation(AnimationUtils.loadAnimation(this, R.anim.bottom_fade_in));
            mVgControlPanel.setVisibility(View.VISIBLE);
        }
        updatePanelInfo();
        delayHide(mVgControlPanel);
    }


    private void delayHide(View view) {

        if (mNeedDelayHideViews.indexOf(view) < 0) {
            mNeedDelayHideViews.add(view);
        }

        //延迟自动隐藏控制面板
        if (mPanelDelayHideRunnable != null) {
            mPanelDelayHideHandler.removeCallbacks(mPanelDelayHideRunnable);
            mPanelDelayHideRunnable = null;
        }

        mPanelDelayHideRunnable = new Runnable() {
            @Override
            public void run() {
                if (mPlayer != null && mPlayer.isPlaying()) {
                    for (View view : mNeedDelayHideViews) {
                        view.startAnimation(AnimationUtils.loadAnimation(VODBuyPlayActivity.this, R.anim.bottom_fade_out));//动画取消
                        view.setVisibility(View.INVISIBLE);
                    }
                }

                mNeedDelayHideViews.clear();
            }
        };
        mPanelDelayHideHandler.postDelayed(mPanelDelayHideRunnable, 2000);
    }






    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_ENTER || keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
            if (!mVgControlPanel.isShown()) {
                mVgControlPanel.startAnimation(AnimationUtils.loadAnimation(this, R.anim.bottom_fade_in));
                mVgControlPanel.setVisibility(View.VISIBLE);
            }
//            if (!mVgControlPanel.isShown()) {
//                mVgControlPanel.startAnimation(AnimationUtils.loadAnimation(this, R.anim.bottom_fade_in));
//            }
            if (mVgControlPanel.getVisibility() == View.VISIBLE) {
                if (mPlayer != null) {
                    if (mPlayer.isPlaying()) {
                        mPlayer.pause();
                        mLastPosition = mPlayer.getCurrentPosition();
                        playbtn.setImageResource(R.drawable.ic_play);
                    } else {
                        mPlayer.start();
                        playbtn.setImageResource(R.drawable.ic_stop);
                    }

                }
            }
        }

        if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT ) {
            if (mVgControlPanel.getVisibility() == View.VISIBLE) {
                int current = mPlayer.getCurrentPosition();
                int duration = mPlayer.getDuration();
                current -= 15000;
                if (current < 0) {
                    current = 0;
                }
                if (mPlayer.isPlaying()) {
                    mPlayer.seekTo(current);
//                    isCanSeek=true;
                }

            }
        }

        if (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT ) {
            if (mVgControlPanel.getVisibility() == View.VISIBLE) {
//                isCanSeek=false;
                try {
                    int current = mPlayer.getCurrentPosition();
                    int duration = mPlayer.getDuration();
                    current += 15000;
                    if (current < duration) {
                        if (mPlayer.isPlaying()) {
                            mPlayer.seekTo(current);
//                            isCanSeek=true;
                        }
                    }
                } catch (Exception e) {

                }


            }
        }

        if (keyCode == KeyEvent.KEYCODE_ENTER
                || keyCode == KeyEvent.KEYCODE_DPAD_CENTER
                || keyCode == KeyEvent.KEYCODE_MENU
                || keyCode == KeyEvent.KEYCODE_DPAD_LEFT
                || keyCode == KeyEvent.KEYCODE_DPAD_RIGHT) {
            showControlPane();
        }

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            isback=true;
        }

        if (keyCode == KeyEvent.KEYCODE_DPAD_UP) {
            //TODO
        } else if (keyCode == KeyEvent.KEYCODE_DPAD_DOWN) {
            //TODO
        }
        if (keyCode == KeyEvent.KEYCODE_MENU) {

//            gotoBuy();

        }




        return super.onKeyDown(keyCode, event);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        releaseMediaPlayer();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mPlayer != null) {
            GlobalParams.playCurrentPosition=mPlayer.getCurrentPosition();
            if (mPlayer.isPlaying()) {

                mPlayer.pause();
                playbtn.setImageResource(R.drawable.ic_play);
            }
        }

    }

    private void releaseMediaPlayer() {

        try {
            if (mPlayer != null) {
                /*if(mPlayer.isPlaying()) {
                    mPlayer.stop();
                }*/


                mPlayer.stop();
                mPlayer.reset();
                mPlayer.release();
                mPlayer = null;
                Log.v(TAG, "释放----商品播放器------------" );

            }
        } catch (IllegalStateException e) {
            e.printStackTrace();
        }


    }


    /**
     * MediaPlayer.OnPreparedListener
     */
    @Override
    public void onPrepared(MediaPlayer mp) {

        mPlayer.start();
        mPlayer.seekTo(GlobalParams.playCurrentPosition);
        playbtn.setImageResource(R.drawable.ic_stop);
    }

    /**
     * MediaPlayer.OnBufferingUpdateListener
     */
    @Override
    public void onBufferingUpdate(MediaPlayer mp, int percent) {
        Log.v(TAG, "buffering process: " + percent);

        String format = "缓冲中...(%1$d％)";
        mBufferingHint.setText(String.format(format, percent));

        if (mPlayer.getCurrentPosition() > 0 && mBufferingPage.getVisibility() == View.VISIBLE) {
            mBufferingPage.setVisibility(View.INVISIBLE);
            showControlPane();
        }
    }

    /**
     * MediaPlayer.OnCompletionListener
     */
    @Override
    public void onCompletion(MediaPlayer mp) {
        //TODO
        Log.v(TAG, "onCompletion");
        if (!isback){
//            gotoBuy();
        }


    }





    /**
     * MediaPlayer.OnInfoListener
     */
    @Override
    public boolean onInfo(MediaPlayer mp, int what, int extra) {
        // TODO Auto-generated method stub
        Log.i("VODPlayer", "snm_onInfo=" + what);
        switch (what) {
            case MediaPlayer.MEDIA_INFO_BUFFERING_END:
            case MediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START:
                mBufferingPage.setVisibility(View.INVISIBLE);
                showControlPane();
                break;
            default:
                Log.i("VODPlayer", "执行了onInfo,并且抛出了(" + what + ")状态码!");
        }
        return false;
    }

    /**
     * r
     * MediaPlayer.OnErrorListener
     */
    @Override
    public boolean onError(MediaPlayer mp, int what, int extra) {
        // TODO Auto-generated method stub
        Log.i("VODPlayer", "snm_onError=" + what);
        switch (what) {
            case 54000:

                break;

            default:
                Log.i("VODPlayer", "执行了onError,并且抛出了(" + what + ")错误码!");
        }

//
        return false;
    }




    private void getPlayUrl(){

        mBufferingHint.setText("正在鉴权,请稍等...");

        try {

            /**
             * ---------------body------------------
             */
            JSONObject body = new JSONObject();
            body.put("sn", GlobalParams.SN);
            body.put("contentid", contentid);
            body.put("accountid", GlobalParams.user_id);



            RequestParams params = new RequestParams(GlobalParams.reqHost + "content/getPlayUrl");
            params.setAsJsonContent(true);
            params.setBodyContent(body.toString().trim());

            /**
             * ---------------send------------------
             */
            x.http().post(params, new org.xutils.common.Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String s) {
                    try {
                        JSONObject jData=new JSONObject(s);

                        JSONObject respbody=jData.getJSONObject("respbody");
                        mVideoUrl=respbody.getJSONObject("data").getString("playurl");

                        mHandler.sendEmptyMessage(1);

                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }

                @Override
                public void onFinished() {

                }

                @Override
                public void onCancelled(CancelledException e) {

                }

                @Override
                public void onError(Throwable throwable, boolean b) {

                }
            });


        }catch (Exception e){
            e.printStackTrace();
        }

    }




    private void getContent(){

        try {

            JSONObject body = new JSONObject();
            body.put("sn", GlobalParams.SN);
            body.put("contentid", contentid);
//            body.put("contentid", "26");
            body.put("accountid", GlobalParams.user_id);


            RequestParams params = new RequestParams(GlobalParams.reqHost + "content/getContent");
            params.setAsJsonContent(true);
            params.setBodyContent(body.toString().trim());

            /**
             * ---------------send------------------
             */
            x.http().post(params, new org.xutils.common.Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String s) {
                    try {
                        JSONObject jData=new JSONObject(s);
                        JSONObject respbody=jData.getJSONObject("respbody");
                        JSONObject data=respbody.getJSONObject("data");

                        String phone=data.getString("phone");
                        String price=data.getString("price");




//                        priceTV.setText("￥"+price);
//                        phoneTV.setText("订购咨询热线 "+phone);





                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }

                @Override
                public void onFinished() {

                }

                @Override
                public void onCancelled(CancelledException e) {

                }

                @Override
                public void onError(Throwable throwable, boolean b) {

                }
            });


        }catch (Exception e){
            e.printStackTrace();
        }

    }




}
